package com.eig.font.filter;

import com.alibaba.fastjson.JSON;
import com.eig.common.util.JWTUtil;
import com.eig.common.vo.Result;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @program: eight-shop-parent
 * @description:
 * @author:
 * @create:
 **/
@Component
public class LoginFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        return chain.filter(exchange);//放行
        //判断请求路径是否为放行。
//        String path = request.getPath().toString();
//        if("/login".equals(path)){
//            return chain.filter(exchange);//放行
//        }
//
//        //获取请求头的token值。
//        String token = request.getHeaders().getFirst("token");
//        if(StringUtils.hasText(token)){
//             //校验token是否有效
//             if(JWTUtil.verifyToken(token)){
//                 return chain.filter(exchange);//放行
//             }
//        }

//        //3.1设置状态码
//        response.setStatusCode(HttpStatus.UNAUTHORIZED);
//        //3.2封装返回数据
//        Result<String> result=new Result<>(4001,"未登录");
//        //3.3作JSON转换
//        byte[] bytes = JSON.toJSONString(result).getBytes(StandardCharsets.UTF_8);
//
//        //3.4调用bufferFactory方法,生成DataBuffer对象
//        DataBuffer buffer = response.bufferFactory().wrap(bytes);
//
//        //4.调用Mono中的just方法,返回要写给前端的JSON数据
//        return response.writeWith(Mono.just(buffer));
    }

    //优先级 值越小优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}
